<template>
  <div class="Agent-ChatFrame-container">
    <div class="ChatFrame-Heading">
        <img src="../assets/ChatFrame/scholarhero-icon.svg" alt="AVG Image" />
        <div class="ChatFrame-Heading-Title">智能体聊天预览</div>
        <a-button type="default">刷新对话</a-button>
    </div>

    <div class="ChatFrame-Content">

    <div class="chatbox-message-wrapper">
    <!-- <div class="chatbox-message-wrapper" v-if="!messages.length"> -->
        <img
            class="chatbox-message-item-avatar"
            :src="scholarheroavatar"
            style="margin: 0 10px 0 0"
        />
        <div class="chatbox-message-no-message-item">
            <div class="chatbox-message-no-message-item-up">
                <MdPreview
                    class="md-editor-preview"
                    modelValue="**HI, 我是统计学小助手**，一位由RAG+AI Agent技术支撑的统计学问答机器人，你可以试着问我："
                />
            </div>
            <div class="chatbox-message-no-message-item-down">
                <div v-for="(question, index) in demoquestions" :key="index">
                    <MdPreview
                        class="md-editor-preview"
                        :modelValue="question"
                        @click="sendMessage_api(question)"
                    />
                </div>
            </div>
        </div>
    </div>

        <div
            v-for="(message, index) in messages"
            :key="index"
            class="chatbox-message-wrapper"
            :class="message.role"
        >
        <img
            class="chatbox-message-item-avatar"
            :src="scholarheroavatar"
            v-if="message.role === 'assistant'"
            style="margin: 0 10px 0 0 ;"
        />
        <div class="chatbox-message-item" :class="message.role">
          <span class="chatbox-message-item-content" 
          v-html="message.content"
          v-if="message.role === 'user'">
          </span>
          <MdPreview
                    class="md-editor-preview"
                    :modelValue="message.content"
                    v-if="message.role === 'assistant'"
                />
        </div>
      </div>

    </div>
    <div class="ChatFrame-Input">
      <textarea
        type="text"
        placeholder="在这里输入你的问题>_<"
        v-model="inputMessage"
        @keydown.enter.prevent="handleEnter"
        @input="resizeTextarea"
        ref="textarea"
        rows="3"
      >
      </textarea>
      <div class="ChatFrame-Input-Submit">
        <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 72 40" fill="none"
        @click="handleEnter">
          <rect width="40" height="40" rx="20" fill="#262626;"/>
          <path fill-rule="evenodd" clip-rule="evenodd" d="M44.7922 29.0427C45.7146 29.0427 46.2956 28.0493 45.8434 27.2454L37.0512 11.6148C36.5901 10.7951 35.4099 10.7951 34.9488 11.6148L26.1566 27.2454C25.7044 28.0493 26.2854 29.0427 27.2078 29.0427H33.5879C34.254 29.0427 34.794 28.5027 34.794 27.8366V24.5911C34.794 24.1606 34.5461 23.7782 34.2498 23.4659C33.8396 23.0335 33.5879 22.4492 33.5879 21.8061C33.5879 20.4739 34.6679 19.394 36 19.394C37.3322 19.394 38.4121 20.4739 38.4121 21.8061C38.4121 22.4492 38.1604 23.0335 37.7502 23.4659C37.4539 23.7782 37.2061 24.1606 37.2061 24.5911V27.8366C37.2061 28.5027 37.746 29.0427 38.4121 29.0427H44.7922Z" fill="white"/>
        </svg>
      </div>
  </div>
  </div>
  </template>
  
<script>

import { h, ref, reactive } from 'vue';
import scholarheroavatar from '../assets/ChatFrame/scholarhero-avatar.svg';
import { MdPreview } from 'md-editor-v3'
import '../assets/md-css/website.css'
import api from '../api/index';

export default {
    name: 'AgentChatFrame',
    components: {
      MdPreview
    },
    data() {
    return {
      demoquestions: [
        '**🧮 统计行政档案包括什么？**',
        '**📖 马克思对威廉•配第的评价很高，在《资本论》中是怎么说的？**',
      ],
      inputMessage: '',
      messages: [],
      HistoryMessages: [
        {
          role: 'system',
          content: `
          你是统计学小助手，
          一位由RAG+AI Agent技术支撑的统计学问答机器人
          `
        },
      ],
        scholarheroavatar: scholarheroavatar,
      }
    },
    methods: {
      resizeTextarea() {
        const textarea = this.$refs.textarea
        const chatboxForm = this.$el.querySelector('.ChatFrame-Input')
        let line = textarea.value.split('\n').length

        if (textarea.rows < 6 || line < 6) {
          textarea.rows = line
        }

        if (textarea.rows > 1) {
          chatboxForm.style.alignItems = 'flex-end'
        } else {
          chatboxForm.style.alignItems = 'center'
        }
      },
      handleEnter(event) {
        if (event.shiftKey) {
          event.preventDefault()
          this.inputMessage += '\n'
          this.resizeTextarea()
        } else {
            this.sendMessage()
        }
      },
      sendMessage() {
        if (this.inputMessage.trim() !== '') {
          const message = {
            role: 'user',
            content: this.inputMessage.trim().replace(/\n/g, '<br>\n'),
          }
          this.messages.push(message)
          this.inputMessage = ''
          this.$nextTick(() => {
            this.scrollToBottom()
            setTimeout(this.autoReply, 1000)
          })
        }
      },
      async autoReply() {
  const inputText = this.inputText;
  const history = this.messages.map(message => message.content);

  try {
    // 创建一个新的消息对象,用于显示助手的回复
    const assistantMessage = {
      role: 'assistant',
      content: '',
    };
    this.messages.push(assistantMessage);

    // 定义光标闪烁状态
    const cursorStates = ['|', ''];
    let blinkIndex = 0;
    const blinkInterval = setInterval(() => {
      blinkIndex = (blinkIndex + 1) % cursorStates.length;
    }, 500);

    // 创建 FormData 对象,用于发送请求数据
    const formData = new FormData();
    formData.append('input_text', inputText);
    formData.append('history', JSON.stringify(history));

    const response = await fetch('http://localhost:5000/chat/completion', {
      method: 'POST',
      body: formData
    });

    const reader = response.body.getReader();
    let result = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      result += new TextDecoder().decode(value);

      // 更新助手消息的内容,并添加闪烁的光标
      assistantMessage.content = result + cursorStates[blinkIndex];
      this.$forceUpdate(); // 触发响应式更新,以更新 DOM
    }

    // 最后一次更新,移除闪烁的光标
    clearInterval(blinkInterval);
    assistantMessage.content = result;
    this.$forceUpdate();

    await this.$nextTick();
    this.scrollToBottom();

    this.inputText = '';
  } catch (error) {
    console.error('自动回复失败:', error);
    // 处理错误,例如从消息列表中移除占位消息
    this.messages.pop();
  }
},
      scrollToBottom() {
        const content = this.$el.querySelector('.ChatFrame-Content')
        content.scrollTop = content.scrollHeight
      },
      getCurrentTime() {
        const now = new Date()
        return `${this.addZero(now.getHours())}:${this.addZero(now.getMinutes())}`
      },
      addZero(num) {
        return num < 10 ? '0' + num : num
      }
    }
}


  </script>
  
  <style lang="scss">

.chatbox-message-no-message-item {
  max-width: 80%;
  padding: 0 !important;
}

.chatbox-message-no-message-item {
  padding-right: 22px;
  padding-left: 6px;
}

.chatbox-message-no-message-item-up {
  background: #f2f2f2;
  max-width: 100%;
  padding: 12px 16px 0px 16px;
  gap: 10px;
  border-radius: 1.15rem 1.15rem 0 0;
  opacity: 0px;
  overflow: hidden;
}

.chatbox-message-no-message-item-down {
  background: #f2f2f2;
  max-width: 100%;
  padding: 0px 16px 12px 16px;
  gap: 10px;
  border-radius: 0px 0px 1.15rem 0;
  opacity: 0px;
  overflow: hidden;
}

  
.Agent-ChatFrame-container {
  --header-height: 70px; /*头部高度*/
    position: relative;

    min-height: calc(100% - 40px);  /* 减去marginTop:20px */
    flex-shrink: 0; /* 加了 flex:1;又加这个的话，那如果宽度不够就会挤压中间那块，尽量不改变这一块的宽度*/
    margin-left: 12px;
    margin-top: 20px;
    border-radius: 12px;
    border: 1px solid #EDEDED;
    background: #FFF;
    box-shadow: 0px 2px 2px 0px #F2F2F2;


.ChatFrame-Heading {
  /*width: 578px; 父级有宽度的话，子级直接 100% 继承父级的宽度就行*/
  width: 100%;
  height: var(--header-height);
  padding: 12px 11px 0; /*上 左右 下*/
   /*margin-left: 11px;
  margin-right: 11px;
  margin-top: 12px;*/
  position: relative;
}

.ChatFrame-Heading {
  .ChatFrame-Heading-Title {
    display: inline-block;
    color: #262626;
    font-family: "PingFang SC";
    font-size: 16px;
    font-style: normal;
    font-weight: 500;
    line-height: 40px; 
  }
} 

.ChatFrame-Heading .ant-btn {
  float: right;
  width: 96px;
  height: 40px;

  border-radius: 12px;
  border: 1px solid #D9D9D9;
  background: #FFF;
  box-shadow: 0px 2px 2px 0px rgba(9, 9, 9, 0.06);
}

.ChatFrame-Content {
  /* width: 578px;
  height: 783px;*/
  /*width: 100%;*/
  height:auto;
  /*min-height: calc(100% - var(--header-height));*/
  margin-left: 11px;
  margin-right: 11px;
}

.chatbox-message-wrapper {
  display: flex;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.chatbox-message-wrapper.user {
  justify-content: flex-end;
}

.chatbox-message-wrapper.assistant {
  justify-content: flex-start;
}

.chatbox-message-item-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 0.5rem;
}

.chatbox-message-item {
  max-width: 80%;
  padding: 0.75rem 1rem;
  border-radius: 1.15rem;
  line-height: 1.25;
  position: relative;
  word-wrap: break-word;
}

.chatbox-message-item.user {
  background: #00BD79;
  color: white;
  border-radius: 1.15rem 1.15rem 0 1.15rem;
}

.chatbox-message-item.assistant {
  background:  #F2F2F2;;
  border-radius: 1.15rem 1.15rem 1.15rem 0;
  box-shadow: 0.25rem 0.25rem 1.5rem rgba(0, 0, 0, 0.05);
}
/*
.chatbox-message-item-time {
  position: absolute;
  bottom: 0;
  right: 0;
  padding: 0.5rem;
  font-size: 0.75rem;
  color: #888;
}
*/
.chatbox-message-no-message {
  font-size: 1rem;
  font-weight: 600;
  text-align: center;
  padding: 1rem;
  color: #888;
}
.ChatFrame-Input {
  display: flex;
  justify-content: flex-start;

  box-sizing: border-box;
  width:100%;
  height: 148px;
  padding: 14px;
  position: absolute;
  bottom: 0;

  textarea {
    flex:1;
    /*width: 462px;*/
    height: 100%;
    padding: 1em;
    border-radius: 12px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    box-shadow: 0px 2px 2px 0px #F2F2F2;
    border-radius: 12px;
    &:focus-visible {
      border: 1px solid rgba(0, 0, 0, 0.15);
    box-shadow: 0px 2px 2px 0px #F2F2F2;
    }

   /* position: absolute;
    left:50%;
    transform: translate(-50%, 0);*/
  }
  
.ChatFrame-Input-Submit {
  /* position:absolute;
  top:0px;
  right: 0px;*/
  width: 40px;
  height: 40px;
  margin-left: 12px;
  z-index:3;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: black;
  border-radius: 12px;
  
}
}
}

  </style>